<html lang="en-US">

<head>
    
<title>「连载五」使用 JWT 进行身份校验 - 花落雨忧</title>

<meta property="og:title" content="「连载五」使用 JWT 进行身份校验 - 花落雨忧">



    



    
    <meta property="description" content="在前面几节中，我们已经基本的完成了 API&amp;rsquo;s 的编写，但是，还存在一些非常严重的问题，例如，我们现在的 API 是可以随意调用的，这显然还不安全全，在本文中我们通过 jwt-go （GoDoc）的方式来简单解决这个问题。
[&amp;hellip;] 首先，我们下载 jwt-go 的依赖包，如下：
go get -u github.com/dgrijalva/jwt-go 编写 jwt 工具 &amp;hellip;">
    <meta property="og:description" content="在前面几节中，我们已经基本的完成了 API&amp;rsquo;s 的编写，但是，还存在一些非常严重的问题，例如，我们现在的 API 是可以随意调用的，这显然还不安全全，在本文中我们通过 jwt-go （GoDoc）的方式来简单解决这个问题。
[&amp;hellip;] 首先，我们下载 jwt-go 的依赖包，如下：
go get -u github.com/dgrijalva/jwt-go 编写 jwt 工具 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/gin/2018-02-14-jwt/">「连载五」使用 JWT 进行身份校验</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/02/14</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="涉及知识点">涉及知识点</h2>
<ul>
<li>JWT</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<p>在前面几节中，我们已经基本的完成了 API&rsquo;s 的编写，但是，还存在一些非常严重的问题，例如，我们现在的 API 是可以随意调用的，这显然还不安全全，在本文中我们通过 <a href="https://github.com/dgrijalva/jwt-go">jwt-go</a> （<a href="https://godoc.org/github.com/dgrijalva/jwt-go">GoDoc</a>）的方式来简单解决这个问题。</p>
<h2 id="下载依赖包">下载依赖包</h2>
<p>首先，我们下载 jwt-go 的依赖包，如下：</p>
<pre><code>go get -u github.com/dgrijalva/jwt-go
</code></pre><h2 id="编写-jwt-工具包">编写 jwt 工具包</h2>
<p>我们需要编写一个<code>jwt</code>的工具包，我们在<code>pkg</code>下的<code>util</code>目录新建<code>jwt.go</code>，写入文件内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">util</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;time&#34;</span>

	<span style="color:#a6e22e">jwt</span> <span style="color:#e6db74">&#34;github.com/dgrijalva/jwt-go&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/setting&#34;</span>
)

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">jwtSecret</span> = []byte(<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">JwtSecret</span>)

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Claims</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Username</span> <span style="color:#66d9ef">string</span> <span style="color:#e6db74">`json:&#34;username&#34;`</span>
	<span style="color:#a6e22e">Password</span> <span style="color:#66d9ef">string</span> <span style="color:#e6db74">`json:&#34;password&#34;`</span>
	<span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">StandardClaims</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GenerateToken</span>(<span style="color:#a6e22e">username</span>, <span style="color:#a6e22e">password</span> <span style="color:#66d9ef">string</span>) (<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">nowTime</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>()
	<span style="color:#a6e22e">expireTime</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">nowTime</span>.<span style="color:#a6e22e">Add</span>(<span style="color:#ae81ff">3</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Hour</span>)

	<span style="color:#a6e22e">claims</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">Claims</span>{
		<span style="color:#a6e22e">username</span>,
		<span style="color:#a6e22e">password</span>,
		<span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">StandardClaims</span> {
			<span style="color:#a6e22e">ExpiresAt</span> : <span style="color:#a6e22e">expireTime</span>.<span style="color:#a6e22e">Unix</span>(),
			<span style="color:#a6e22e">Issuer</span> : <span style="color:#e6db74">&#34;gin-blog&#34;</span>,
		},
	}

	<span style="color:#a6e22e">tokenClaims</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">NewWithClaims</span>(<span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">SigningMethodHS256</span>, <span style="color:#a6e22e">claims</span>)
	<span style="color:#a6e22e">token</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">tokenClaims</span>.<span style="color:#a6e22e">SignedString</span>(<span style="color:#a6e22e">jwtSecret</span>)

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">token</span>, <span style="color:#a6e22e">err</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">ParseToken</span>(<span style="color:#a6e22e">token</span> <span style="color:#66d9ef">string</span>) (<span style="color:#f92672">*</span><span style="color:#a6e22e">Claims</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">tokenClaims</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">ParseWithClaims</span>(<span style="color:#a6e22e">token</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Claims</span>{}, <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">token</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">Token</span>) (<span style="color:#66d9ef">interface</span>{}, <span style="color:#66d9ef">error</span>) {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">jwtSecret</span>, <span style="color:#66d9ef">nil</span>
	})

	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">tokenClaims</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">claims</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">tokenClaims</span>.<span style="color:#a6e22e">Claims</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">Claims</span>); <span style="color:#a6e22e">ok</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#a6e22e">tokenClaims</span>.<span style="color:#a6e22e">Valid</span> {
			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">claims</span>, <span style="color:#66d9ef">nil</span>
		}
	}

	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
}
</code></pre></div><p>在这个工具包，我们涉及到</p>
<ul>
<li><code>NewWithClaims(method SigningMethod, claims Claims)</code>，<code>method</code>对应着<code>SigningMethodHMAC struct{}</code>，其包含<code>SigningMethodHS256</code>、<code>SigningMethodHS384</code>、<code>SigningMethodHS512</code>三种<code>crypto.Hash</code>方案</li>
<li><code>func (t *Token) SignedString(key interface{})</code> 该方法内部生成签名字符串，再用于获取完整、已签名的<code>token</code></li>
<li><code>func (p *Parser) ParseWithClaims</code> 用于解析鉴权的声明，<a href="https://gowalker.org/github.com/dgrijalva/jwt-go#Parser_ParseWithClaims">方法内部</a>主要是具体的解码和校验的过程，最终返回<code>*Token</code></li>
<li><code>func (m MapClaims) Valid()</code> 验证基于时间的声明<code>exp, iat, nbf</code>，注意如果没有任何声明在令牌中，仍然会被认为是有效的。并且对于时区偏差没有计算方法</li>
</ul>
<p>有了<code>jwt</code>工具包，接下来我们要编写要用于<code>Gin</code>的中间件，我们在<code>middleware</code>下新建<code>jwt</code>目录，新建<code>jwt.go</code>文件，写入内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">jwt</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;time&#34;</span>
	<span style="color:#e6db74">&#34;net/http&#34;</span>

	<span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/util&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/e&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">JWT</span>() <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">HandlerFunc</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
		<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">code</span> <span style="color:#66d9ef">int</span>
		<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">data</span> <span style="color:#66d9ef">interface</span>{}

		<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span>
		<span style="color:#a6e22e">token</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Query</span>(<span style="color:#e6db74">&#34;token&#34;</span>)
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">token</span> <span style="color:#f92672">==</span> <span style="color:#e6db74">&#34;&#34;</span> {
			<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">INVALID_PARAMS</span>
		} <span style="color:#66d9ef">else</span> {
			<span style="color:#a6e22e">claims</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">util</span>.<span style="color:#a6e22e">ParseToken</span>(<span style="color:#a6e22e">token</span>)
			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
				<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_AUTH_CHECK_TOKEN_FAIL</span>
			} <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Unix</span>() &gt; <span style="color:#a6e22e">claims</span>.<span style="color:#a6e22e">ExpiresAt</span> {
				<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_AUTH_CHECK_TOKEN_TIMEOUT</span>
			}
		}

		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">code</span> <span style="color:#f92672">!=</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span> {
			<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusUnauthorized</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
		        <span style="color:#e6db74">&#34;code&#34;</span> : <span style="color:#a6e22e">code</span>,
		        <span style="color:#e6db74">&#34;msg&#34;</span> : <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
		        <span style="color:#e6db74">&#34;data&#34;</span> : <span style="color:#a6e22e">data</span>,
		    })

		    <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Abort</span>()
		    <span style="color:#66d9ef">return</span>
		}

		<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Next</span>()
	}
}
</code></pre></div><h2 id="如何获取token">如何获取<code>Token</code></h2>
<p>那么我们如何调用它呢，我们还要获取<code>Token</code>呢？</p>
<p>1、 我们要新增一个获取<code>Token</code>的 API</p>
<p>在<code>models</code>下新建<code>auth.go</code>文件，写入内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">models</span>

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Auth</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">ID</span> <span style="color:#66d9ef">int</span> <span style="color:#e6db74">`gorm:&#34;primary_key&#34; json:&#34;id&#34;`</span>
	<span style="color:#a6e22e">Username</span> <span style="color:#66d9ef">string</span> <span style="color:#e6db74">`json:&#34;username&#34;`</span>
	<span style="color:#a6e22e">Password</span> <span style="color:#66d9ef">string</span> <span style="color:#e6db74">`json:&#34;password&#34;`</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CheckAuth</span>(<span style="color:#a6e22e">username</span>, <span style="color:#a6e22e">password</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">bool</span> {
	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">auth</span> <span style="color:#a6e22e">Auth</span>
	<span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Select</span>(<span style="color:#e6db74">&#34;id&#34;</span>).<span style="color:#a6e22e">Where</span>(<span style="color:#a6e22e">Auth</span>{<span style="color:#a6e22e">Username</span> : <span style="color:#a6e22e">username</span>, <span style="color:#a6e22e">Password</span> : <span style="color:#a6e22e">password</span>}).<span style="color:#a6e22e">First</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">auth</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">auth</span>.<span style="color:#a6e22e">ID</span> &gt; <span style="color:#ae81ff">0</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>
	}

	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>
}
</code></pre></div><p>在<code>routers</code>下的<code>api</code>目录新建<code>auth.go</code>文件，写入内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">api</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;log&#34;</span>
	<span style="color:#e6db74">&#34;net/http&#34;</span>

	<span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>
	<span style="color:#e6db74">&#34;github.com/astaxie/beego/validation&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/e&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/util&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/models&#34;</span>
)

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">auth</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Username</span> <span style="color:#66d9ef">string</span> <span style="color:#e6db74">`valid:&#34;Required; MaxSize(50)&#34;`</span>
	<span style="color:#a6e22e">Password</span> <span style="color:#66d9ef">string</span> <span style="color:#e6db74">`valid:&#34;Required; MaxSize(50)&#34;`</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetAuth</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
	<span style="color:#a6e22e">username</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Query</span>(<span style="color:#e6db74">&#34;username&#34;</span>)
	<span style="color:#a6e22e">password</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Query</span>(<span style="color:#e6db74">&#34;password&#34;</span>)

	<span style="color:#a6e22e">valid</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">validation</span>.<span style="color:#a6e22e">Validation</span>{}
	<span style="color:#a6e22e">a</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">auth</span>{<span style="color:#a6e22e">Username</span>: <span style="color:#a6e22e">username</span>, <span style="color:#a6e22e">Password</span>: <span style="color:#a6e22e">password</span>}
	<span style="color:#a6e22e">ok</span>, <span style="color:#a6e22e">_</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Valid</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">a</span>)

	<span style="color:#a6e22e">data</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">map</span>[<span style="color:#66d9ef">string</span>]<span style="color:#66d9ef">interface</span>{})
	<span style="color:#a6e22e">code</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">INVALID_PARAMS</span>
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">ok</span> {
		<span style="color:#a6e22e">isExist</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">CheckAuth</span>(<span style="color:#a6e22e">username</span>, <span style="color:#a6e22e">password</span>)
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">isExist</span> {
			<span style="color:#a6e22e">token</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">util</span>.<span style="color:#a6e22e">GenerateToken</span>(<span style="color:#a6e22e">username</span>, <span style="color:#a6e22e">password</span>)
			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
				<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_AUTH_TOKEN</span>
			} <span style="color:#66d9ef">else</span> {
				<span style="color:#a6e22e">data</span>[<span style="color:#e6db74">&#34;token&#34;</span>] = <span style="color:#a6e22e">token</span>

				<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span>
			}

		} <span style="color:#66d9ef">else</span> {
			<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_AUTH</span>
		}
	} <span style="color:#66d9ef">else</span> {
		<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Errors</span> {
            <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Key</span>, <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Message</span>)
        }
	}

	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
        <span style="color:#e6db74">&#34;code&#34;</span> : <span style="color:#a6e22e">code</span>,
        <span style="color:#e6db74">&#34;msg&#34;</span> : <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
        <span style="color:#e6db74">&#34;data&#34;</span> : <span style="color:#a6e22e">data</span>,
    })
}
</code></pre></div><p>我们打开<code>routers</code>目录下的<code>router.go</code>文件，修改文件内容（新增获取 token 的方法）：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">routers</span>

<span style="color:#f92672">import</span> (
    <span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>

    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/routers/api&#34;</span>
    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/routers/api/v1&#34;</span>
    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/setting&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">InitRouter</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Engine</span> {
    <span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">New</span>()

    <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Logger</span>())

    <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Recovery</span>())

    <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">SetMode</span>(<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RunMode</span>)

    <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/auth&#34;</span>, <span style="color:#a6e22e">api</span>.<span style="color:#a6e22e">GetAuth</span>)

    <span style="color:#a6e22e">apiv1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Group</span>(<span style="color:#e6db74">&#34;/api/v1&#34;</span>)
    {
        <span style="color:#f92672">...</span>
    }

    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
}
</code></pre></div><h2 id="验证token">验证<code>Token</code></h2>
<p>获取<code>token</code>的 API 方法就到这里啦，让我们来测试下是否可以正常使用吧！</p>
<p>重启服务后，用<code>GET</code>方式访问<code>http://127.0.0.1:8000/auth?username=test&amp;password=test123456</code>，查看返回值是否正确</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-json" data-lang="json">{
  <span style="color:#f92672">&#34;code&#34;</span>: <span style="color:#ae81ff">200</span>,
  <span style="color:#f92672">&#34;data&#34;</span>: {
    <span style="color:#f92672">&#34;token&#34;</span>: <span style="color:#e6db74">&#34;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJwYXNzd29yZCI6InRlc3QxMjM0NTYiLCJleHAiOjE1MTg3MjAwMzcsImlzcyI6Imdpbi1ibG9nIn0.-kK0V9E06qTHOzupQM_gHXAGDB3EJtJS4H5TTCyWwW8&#34;</span>
  },
  <span style="color:#f92672">&#34;msg&#34;</span>: <span style="color:#e6db74">&#34;ok&#34;</span>
}
</code></pre></div><p>我们有了<code>token</code>的 API，也调用成功了</p>
<h2 id="将中间件接入gin">将中间件接入<code>Gin</code></h2>
<p>2、 接下来我们将中间件接入到<code>Gin</code>的访问流程中</p>
<p>我们打开<code>routers</code>目录下的<code>router.go</code>文件，修改文件内容（新增引用包和中间件引用）</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">routers</span>

<span style="color:#f92672">import</span> (
    <span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>

    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/routers/api&#34;</span>
    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/routers/api/v1&#34;</span>
    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/setting&#34;</span>
    <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/middleware/jwt&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">InitRouter</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Engine</span> {
    <span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">New</span>()

    <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Logger</span>())

    <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Recovery</span>())

    <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">SetMode</span>(<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RunMode</span>)

    <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/auth&#34;</span>, <span style="color:#a6e22e">api</span>.<span style="color:#a6e22e">GetAuth</span>)

    <span style="color:#a6e22e">apiv1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Group</span>(<span style="color:#e6db74">&#34;/api/v1&#34;</span>)
    <span style="color:#a6e22e">apiv1</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">JWT</span>())
    {
        <span style="color:#f92672">...</span>
    }

    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
}
</code></pre></div><p>当前目录结构：</p>
<pre><code>go-gin-example/
├── conf
│   └── app.ini
├── main.go
├── middleware
│   └── jwt
│       └── jwt.go
├── models
│   ├── article.go
│   ├── auth.go
│   ├── models.go
│   └── tag.go
├── pkg
│   ├── e
│   │   ├── code.go
│   │   └── msg.go
│   ├── setting
│   │   └── setting.go
│   └── util
│       ├── jwt.go
│       └── pagination.go
├── routers
│   ├── api
│   │   ├── auth.go
│   │   └── v1
│   │       ├── article.go
│   │       └── tag.go
│   └── router.go
├── runtime
</code></pre><p>到这里，我们的<code>JWT</code>编写就完成啦！</p>
<h2 id="验证功能">验证功能</h2>
<p>我们来测试一下，再次访问</p>
<ul>
<li>http://127.0.0.1:8000/api/v1/articles</li>
<li>http://127.0.0.1:8000/api/v1/articles?token=23131</li>
</ul>
<p>正确的反馈应该是</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-json" data-lang="json">{
  <span style="color:#f92672">&#34;code&#34;</span>: <span style="color:#ae81ff">400</span>,
  <span style="color:#f92672">&#34;data&#34;</span>: <span style="color:#66d9ef">null</span>,
  <span style="color:#f92672">&#34;msg&#34;</span>: <span style="color:#e6db74">&#34;请求参数错误&#34;</span>
}

{
  <span style="color:#f92672">&#34;code&#34;</span>: <span style="color:#ae81ff">20001</span>,
  <span style="color:#f92672">&#34;data&#34;</span>: <span style="color:#66d9ef">null</span>,
  <span style="color:#f92672">&#34;msg&#34;</span>: <span style="color:#e6db74">&#34;Token鉴权失败&#34;</span>
}

</code></pre></div><p>我们需要访问<code>http://127.0.0.1:8000/auth?username=test&amp;password=test123456</code>，得到<code>token</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-json" data-lang="json">{
  <span style="color:#f92672">&#34;code&#34;</span>: <span style="color:#ae81ff">200</span>,
  <span style="color:#f92672">&#34;data&#34;</span>: {
    <span style="color:#f92672">&#34;token&#34;</span>: <span style="color:#e6db74">&#34;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJwYXNzd29yZCI6InRlc3QxMjM0NTYiLCJleHAiOjE1MTg3MjQ2OTMsImlzcyI6Imdpbi1ibG9nIn0.KSBY6TeavV_30kfmP7HWLRYKP5TPEDgHtABe9HCsic4&#34;</span>
  },
  <span style="color:#f92672">&#34;msg&#34;</span>: <span style="color:#e6db74">&#34;ok&#34;</span>
}
</code></pre></div><p>再用包含<code>token</code>的 URL 参数去访问我们的应用 API，</p>
<p>访问<code>http://127.0.0.1:8000/api/v1/articles?token=eyJhbGci...</code>，检查接口返回值</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-json" data-lang="json">{
  <span style="color:#f92672">&#34;code&#34;</span>: <span style="color:#ae81ff">200</span>,
  <span style="color:#f92672">&#34;data&#34;</span>: {
    <span style="color:#f92672">&#34;lists&#34;</span>: [
      {
        <span style="color:#f92672">&#34;id&#34;</span>: <span style="color:#ae81ff">2</span>,
        <span style="color:#f92672">&#34;created_on&#34;</span>: <span style="color:#ae81ff">1518700920</span>,
        <span style="color:#f92672">&#34;modified_on&#34;</span>: <span style="color:#ae81ff">0</span>,
        <span style="color:#f92672">&#34;tag_id&#34;</span>: <span style="color:#ae81ff">1</span>,
        <span style="color:#f92672">&#34;tag&#34;</span>: {
          <span style="color:#f92672">&#34;id&#34;</span>: <span style="color:#ae81ff">1</span>,
          <span style="color:#f92672">&#34;created_on&#34;</span>: <span style="color:#ae81ff">1518684200</span>,
          <span style="color:#f92672">&#34;modified_on&#34;</span>: <span style="color:#ae81ff">0</span>,
          <span style="color:#f92672">&#34;name&#34;</span>: <span style="color:#e6db74">&#34;tag1&#34;</span>,
          <span style="color:#f92672">&#34;created_by&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
          <span style="color:#f92672">&#34;modified_by&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
          <span style="color:#f92672">&#34;state&#34;</span>: <span style="color:#ae81ff">0</span>
        },
        <span style="color:#f92672">&#34;content&#34;</span>: <span style="color:#e6db74">&#34;test-content&#34;</span>,
        <span style="color:#f92672">&#34;created_by&#34;</span>: <span style="color:#e6db74">&#34;test-created&#34;</span>,
        <span style="color:#f92672">&#34;modified_by&#34;</span>: <span style="color:#e6db74">&#34;&#34;</span>,
        <span style="color:#f92672">&#34;state&#34;</span>: <span style="color:#ae81ff">0</span>
      }
    ],
    <span style="color:#f92672">&#34;total&#34;</span>: <span style="color:#ae81ff">1</span>
  },
  <span style="color:#f92672">&#34;msg&#34;</span>: <span style="color:#e6db74">&#34;ok&#34;</span>
}
</code></pre></div><p>返回正确，至此我们的<code>jwt-go</code>在<code>Gin</code>中的验证就完成了！</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 01 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-02-13-api-03/">「连载四」Gin搭建Blog API&#39;s （三）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-02-12-api-02/">「连载三」Gin搭建Blog API&#39;s （二）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-02-11-api-01/">「连载二」Gin搭建Blog API&#39;s （一）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-02-10-install/">「连载一」Go 介绍与环境安装</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/gin/2018-02-13-api-03/"
                                                    rel="prev">「连载四」Gin搭建Blog API&#39;s （三）</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/gin/2018-02-15-log/">「连载六」编写一个简单的文件日志</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>